#include "common/unp.h"
int tcpecho( int sockfd, char* clientname);

int main( int argc, char *argv[] )
{
	int listensock, clientsock;
	listensock = socket( AF_INET, SOCK_STREAM, 0 );
	if( listensock < 0 ){
		perror("socket() fail \n");
	}
	struct sockaddr_in listenaddr, clientaddr;
	memset( &listenaddr, 0, sizeof(listenaddr) );
	memset( &clientaddr, 0, sizeof(clientaddr) );
	listenaddr.sin_family = AF_INET;
	listenaddr.sin_port = htons(4321);
	listenaddr.sin_addr.s_addr = INADDR_ANY;

	if( bind( listensock, (struct sockaddr* )&listenaddr, \
				sizeof(listenaddr) ) < 0 ){
		perror(" bind() fail \n" );
	}
	if( listen( listensock, 10 ) < 0 ){
		perror("listen() fail \n");
	}
	char clientbuff[1024];
	while( 1 ){
		int clientaddrlen = sizeof( clientaddr );
		clientsock = accept( listensock, (struct sockaddr *)&clientaddr, \
				&clientaddrlen );
		if( clientsock < 0 ){
			if(errno == EINTR)
				continue;
			else
			{
				perror("accept() fail \n");
				break;
			}
		}
		switch( fork() ){
			case 0:
				close( listensock );
				tcpecho( clientsock, inet_ntoa( clientaddr.sin_addr ) );
			case -1:
				perror(" fork() error \n ");
			default:
				close( clientsock );
				break;
		}
		/*
		int recvnum = recv( clientsock, clientbuff, 1024 , 0);
		if( recvnum < 0 ){
			continue;
		}
		clientbuff[recvnum] = '\0';
		printf("%s : %s \n", inet_ntoa(clientaddr.sin_addr), clientbuff );
		clientbuff[recvnum]='_';
		clientbuff[recvnum+1]= 's';
		clientbuff[recvnum+2]= '\0';
		send( clientsock, clientbuff, strlen( clientbuff ) ,0 ); 
		*/
	}
}

int tcpecho( int sockfd, char* clientname ){
	char buf[1024];
	int recvnum = 0 ;
	memset(buf, 0, sizeof(buf));
	while( recvnum = read( sockfd, buf, sizeof(buf) ) ){
		if( recvnum < 0 ){
			printf("read() < 0 ");
			return 0;
		}
		buf[recvnum] = '\0';
		printf("%s:%s \n", clientname, buf);
		buf[recvnum] = '_';
		buf[recvnum+1] = 's';
		buf[recvnum+2] = '\0';	
		write( sockfd, buf, sizeof(buf) );
	}
	return 0;
}
